//
//  MyPageControl.m
//  MyPageControllTest
//
//  Created by apple on 11-10-11.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyPageControl.h"
@interface MyPageControl(private)
-(void)updateDotImages;
-(void)initDotImages;
@end


@implementation MyPageControl
-(id)initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self initDotImages];
    }
    return self;
}
-(void)setNumberOfPages:(NSInteger)numberOfPages
{
    [super setNumberOfPages:numberOfPages];
    [self updateDotImages];
}

-(void)didAddSubview:(UIView *)subview
{
    [super didAddSubview:subview];

    UIImageView* dotView = (UIImageView*)subview;
    [dotView setContentMode:UIViewContentModeCenter];
    NSInteger index = [self.subviews indexOfObject:dotView];
    dotView.image = self.currentPage == index ? m_highLightDotImage : m_normalDotImage;
}
-(id)initWithFrame:(CGRect)frame
{
    
    if ((self = [super initWithFrame:frame]))
    {

        [self initDotImages];
        
    }
    return self;
}
-(void)updateCurrentPageDisplay
{
    [super updateCurrentPageDisplay];

}
-(void)setCurrentPage:(NSInteger)currentPage
{
    [super setCurrentPage:currentPage];
    [self updateDotImages];
}
-(void)changedIndex:(id)sender
{
    [self updateDotImages];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
}
-(void) initDotImages
{
    [self addObserver:self forKeyPath:@"currentPage" options:NSKeyValueObservingOptionInitial context:nil];

    
    [self setDefersCurrentPageDisplay:NO];
    NSString* imgPath = [[NSBundle mainBundle] pathForResource:@"page_controller_highlight_dot" ofType:@"png"];
    m_highLightDotImage = [[UIImage alloc] initWithContentsOfFile:imgPath];
    imgPath = [[NSBundle mainBundle] pathForResource:@"page_controller_graddot" ofType:@"png"];
    m_normalDotImage = [[UIImage alloc] initWithContentsOfFile:imgPath];
    
    [self addTarget:self action:@selector(changedIndex:) forControlEvents:UIControlEventValueChanged];
    
    NSArray* dotViewsList = [self subviews];
    for (int i = 0; i < dotViewsList.count; i++)
    {
        UIImageView* dotView = [dotViewsList objectAtIndex:i];
        [dotView setContentMode:UIViewContentModeCenter];
    }
    
    [self updateDotImages];

}
-(void)updateDotImages
{
    NSArray* dotViewsList = [self subviews];
    for (int i = 0; i < dotViewsList.count; i++)
    {
        UIImageView* dotView = [dotViewsList objectAtIndex:i];
        dotView.image = self.currentPage == i ? m_highLightDotImage : m_normalDotImage;
    }
}
-(void)dealloc
{
    
    if (m_highLightDotImage || m_normalDotImage)
    {
        [m_highLightDotImage release];
        [m_normalDotImage release];
        m_highLightDotImage = Nil;
        m_normalDotImage = Nil;
        
    }
    
    [super dealloc];
}
@end
